const lodash = require('lodash');
const view = {

  init(tablename, listSQL, querySQL, componentNames, componentsDef, componentsHtml, requiredSQL,primaryKey) {
    let camelCaseTableName = lodash.camelCase(tablename);
    let camelCaseTableNameFirst = lodash.upperFirst(camelCaseTableName);
    let modelName = camelCaseTableName + "Model";
    let page = `
import React from 'react';
import { connect } from 'dva';
import { Form, Button, Table, Divider, Tag, ${componentNames.join(",")} } from 'antd';
import AddPage from './add';
import EditPage from './edit';
import DetailPage from './detail';
import moment from "moment";
import MoButton from "components/form/MoButton";
${componentsDef}

// 与model建立连接
@connect(({ ${modelName} }) => ({
  page: ${modelName}.page,
  pageSize: ${modelName}.pageSize,
  tabledata: ${modelName}.tabledata,
  addShowVisible: ${modelName}.addShowVisible,
  editShowVisible: ${modelName}.editShowVisible,
  detailShowVisible: ${modelName}.detailShowVisible
}))

//初始化Form
@Form.create()
class List extends React.PureComponent {

  componentDidMount() {
    //初始化页面数据
    const { dispatch } = this.props;
    dispatch({
      type: '${modelName}/initPageData',
      payload: {},
    });
  }

  addShow = () => {
    console.log("新增");
    const { dispatch } = this.props;
    dispatch({
      type: '${modelName}/addShow',
      payload: {}
    });
  }

  editShow = (value,loadBack) => {
    console.log("编辑");
    const { dispatch } = this.props;
    dispatch({
      type: '${modelName}/editShow',
      payload: { ${primaryKey.t_column_name}: value }
    });
  }

  delRowData = (value,loadBack) => {
    console.log("删除");
    const { dispatch } = this.props;
    dispatch({
      type: '${modelName}/delRowData',
      payload: { ${primaryKey.t_column_name}: value }
    });
  }

  querySubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        const { dispatch } = this.props;
        dispatch({
          type: '${modelName}/querySubmit',
          payload: { queryParams: values }
        });
      }
    });
  };

  /**
   * 页数据长度发生改变
   */
   pageSizeChange = (current, pageSize) => {
       const { dispatch } = this.props;
       dispatch({
           type: '${modelName}/pageOrPageSizeChange',
           payload: { page: 1, pageSize }
       });
   };

   /**
    * 页码发生改变
    */
   pageChange = (page, pageSize) => {
       const { dispatch } = this.props;
       dispatch({
           type: '${modelName}/pageOrPageSizeChange',
           payload: { page, pageSize }
       });
   };

  render() {
    const { addShow, editShow, delRowData, querySubmit, pageSizeChange, pageChange } = this;
    const { tabledata,page,pageSize } = this.props;
    const { getFieldDecorator} = this.props.form;
    //定义数据显示项
    ${getListColumns(listSQL,primaryKey)}
    return (

      <div>
        <div className="flex">
          <Form layout="inline">
            
            ${componentsHtml}

            <Form.Item>
              <Button type="primary" icon="search" size="small" onClick={querySubmit}>查 询</Button>
              <Button type="primary" icon="plus" size="small" className="mgl10" onClick={addShow} >新增</Button>
            </Form.Item>
          </Form>

        </div>
        <div style={{ marginTop: "15px" }}>
            <Table rowKey="${primaryKey.t_column_name}" columns={columns} dataSource={tabledata.datalist} pagination={{
              "size": "small",
              "current": page,
              "pageSize": pageSize,
              "total": tabledata.totalSize,
              "showSizeChanger": true,
              "showQuickJumper": true,
              "onChange": pageChange,
              "onShowSizeChange": pageSizeChange
          }} />
        </div>
        <div>
          <AddPage></AddPage>
          <EditPage></EditPage>
          <DetailPage></DetailPage>
        </div>
      </div>

    );
  }
}

export default List;
`;
    return page;
  }

}

module.exports = view;

function getListColumns(listSQL,primaryKey) {
  let columns = [];
  for (var i = 0; i < listSQL.length; i++) {
    let item = listSQL[i];
    if (item.t_data_type.indexOf("date") > -1) {
      columns.push(`\n{
        title: '${item.column_comment}',
        dataIndex: '${item.t_column_name}',
        key: '${item.t_column_name}',
        align: "center",
        render: (value, rowData, index) => (
          <span>
              {value!=null&&moment(value).format('YYYY-MM-DD HH:mm:ss')}
          </span>
        )
      }`);
    } else {
      columns.push(`{
        title: '${item.column_comment}',
        dataIndex: '${item.t_column_name}',
        key: '${item.t_column_name}',
        align: "center"
    }`);
    }
  }

  columns.push(`{
    title: '操作',
    key: 'table_id',
    render: (value, rowData, index) => (
      <span>
        <MoButton ghost="true" type="primary" size="small" moAuto={3} moClick={(loadBack) => editShow(rowData.${primaryKey.t_column_name}, loadBack)}>编辑</MoButton>
        <Divider type="vertical" />
        <MoButton ghost="true" type="danger" size="small" moAuto={3} moClick={(loadBack) => delRowData(rowData.${primaryKey.t_column_name}, loadBack)}>删除</MoButton>
      </span>
    ),
  }`)
  return `const columns = [${columns.join(",")}]`;
}